package com.ts.proj.controller;

import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.SystemGlobalEntity;
import com.ts.proj.entity.SystemMenuEntity;
import com.ts.proj.entity.SystemRoleEntity;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.service.SystemGlobalService;
import com.ts.proj.service.SystemMenuService;
import com.ts.proj.service.SystemRoleService;
import com.ts.proj.service.SystemUserService;
import com.ts.util.JsonUtils;
import com.ts.util.JurisdictionUtil;
import com.ts.util.PageData;
import com.ts.util.RightsHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
@Slf4j
public class IndexController extends BaseController {
    @Autowired
    private SystemRoleService systemRoleService;
    @Autowired
    private SystemMenuService systemMenuService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemGlobalService systemGlobalService;

    @Autowired
    private SystemUserService systemUserService;

    /**
     * 重定向
     * @return
     */
    @RequestMapping(value = "/")
    public ModelAndView index(){
        ModelAndView mv  = this.getModelAndView();

        //-----------从redis里面查询
        List<SystemGlobalEntity> all = systemGlobalService.findAll();
        SystemGlobalEntity systemGlobalEntity = null;
        if(all.size()!=1){
            systemGlobalEntity = new SystemGlobalEntity();
        }else{
            systemGlobalEntity = all.get(0);
        }
        PageData pd = new PageData();
        pd.put("deleteFlag", InsUpdDelFlagConstant.LOCALLOGDELETEFLAG);
        List<SystemUserEntity> systemUserEntities = systemUserService.findAll(pd);
        mv.addObject("users", systemUserEntities);
        mv.addObject("entity", systemGlobalEntity);
        //-----------从redis里面查询

        mv.setViewName("login");
        return mv;
    }

    @RequestMapping(value = "/logout_tologout")
    public ModelAndView logout(){
        ModelAndView modelAndView = this.getModelAndView();
        this.getRequest().getSession().removeAttribute(ConsoleConstant.SESSIONUSER);
        this.getRequest().getSession().removeAttribute(ConsoleConstant.RIGHTS);
        this.getRequest().getSession().removeAttribute(ConsoleConstant.ROLEID);
        this.getRequest().getSession().removeAttribute(ConsoleConstant.BUTTONRIGHTS);

        //-----------从redis里面查询
        List<SystemGlobalEntity> all = systemGlobalService.findAll();
        SystemGlobalEntity systemGlobalEntity = null;
        if(all.size()!=1){
            systemGlobalEntity = new SystemGlobalEntity();
        }else{
            systemGlobalEntity = all.get(0);
        }
        PageData pd = new PageData();
        pd.put("deleteFlag", InsUpdDelFlagConstant.LOCALLOGDELETEFLAG);
        List<SystemUserEntity> systemUserEntities = systemUserService.findAll(pd);
        modelAndView.addObject("users", systemUserEntities);
        modelAndView.addObject("entity", systemGlobalEntity);
        //-----------从redis里面查询
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping("/main")
    public ModelAndView main(){
        //获取角色以及menu list
        ModelAndView mv = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            String user = (String) this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER);
            SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(user, SystemUserEntity.class);
            Integer roleId = systemUserEntity.getRoleId();
            //通过Role查找rights，在查menu
            PageData pageData = new PageData();
            pageData.put("id", roleId);
            List<SystemRoleEntity> allOrOne = systemRoleService.findAll(pageData);
            if(allOrOne==null||allOrOne.size()==0){
                mv.setViewName("login");
                return mv;
            }
            //为了防止转成科学计数法，将权限码添加了首位标记：R-页面权限，B-按钮权限
            String rights = allOrOne.get(0).getRights().substring(1);
            //通过rights来获取menu
            List<Integer> ids = new ArrayList<>();
            for(int i=1;i<1000;i++){
                if(RightsHelper.testRights(rights, i)){
                    ids.add(i);
                }
            }
            Integer[] idsArray = new Integer[ids.size()];
            for(int i=0;i<ids.size();i++){
                idsArray[i] = ids.get(i);
            }

            //-----------从redis里面查询
            List<SystemGlobalEntity> all = systemGlobalService.findAll();
            SystemGlobalEntity systemGlobalEntity = null;
            if(all.size()!=1){
                systemGlobalEntity = new SystemGlobalEntity();
            }else{
                systemGlobalEntity = all.get(0);
            }
            mv.addObject("entity", systemGlobalEntity);
            //-----------从redis里面查询

            //通过ids查询所有的menu
            mv.addObject("user", systemUserEntity.getNickname());
            mv.addObject("loginName", systemUserEntity.getUsername());
            mv.addObject("count", 1);
            mv.addObject("shortlist", shortList(systemUserEntity.getUserShortCut()));
            mv.addObject("menu", menuLists(systemMenuService.findAllById(idsArray)));
            viewName = "index/main";
        }
        mv.setViewName(viewName);
        return mv;
    }

    /**
     * iframe 跳转页面
     * @return
     */
    @RequestMapping(value="/iframe")
    public ModelAndView mainIframe(){
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("index/welcome");
        return mv;
    }

    //--------------------------------------------------------------------------//
    private List<PageData> menuLists (List<SystemMenuEntity> systemMenuEntities){
        List<PageData> nodes = new ArrayList<PageData>();
        int i = 0;
        for(SystemMenuEntity menuEntity : systemMenuEntities){
            //获取父目录
            if("0".equals(menuEntity.getParentId())&& InsUpdDelFlagConstant.DELETE_FLAG_N.equals(menuEntity.getDeleteFlag())){
                //获取MENU_ID
                Integer menuId = menuEntity.getId();
                PageData pd = new PageData();
                pd.put("MENU_ID",String.valueOf(menuEntity.getId()));
                pd.put("PARENT_ID",menuEntity.getParentId());
                pd.put("MENU_NAME",menuEntity.getMenuName());
                pd.put("MENU_ICON",menuEntity.getMenuIcon());
                List<PageData> subMenuEntityPageData = new ArrayList<>();
                for(SystemMenuEntity menu: systemMenuEntities){
                    if(menuId == Integer.valueOf(menu.getParentId())&& InsUpdDelFlagConstant.DELETE_FLAG_N.equals(menu.getDeleteFlag())){
                        PageData subPageData = new PageData();
                        subPageData.put("MENU_ID",String.valueOf(menuEntity.getId()));
                        subPageData.put("PARENT_ID",menu.getParentId());
                        subPageData.put("MENU_URL",menu.getMenuURL());
                        subPageData.put("MENU_NAME",menu.getMenuName());
                        subPageData.put("MENU_ICON",menu.getMenuIcon());
                        subPageData.put("ID", i++);
                        subMenuEntityPageData.add(subPageData);
                    }
                }
                pd.put("subMenu",subMenuEntityPageData);
                nodes.add(pd);
            }
        }

        return nodes;
    }

    private List<PageData> shortList(String userShortCut) {

        List<PageData> resultList = new ArrayList<>();
            List<Integer> idsList = new ArrayList<>();
            for(int i=0;i<200;i++){
                if(RightsHelper.testRights(userShortCut.substring(1),i)){
                    idsList.add(i);
                }
            }
            Integer[] idsArray = new Integer[idsList.size()];
                idsList.toArray(idsArray);
            List<SystemMenuEntity> systemMenuList = systemMenuService.findAllById(idsArray);
            for(SystemMenuEntity menu : systemMenuList){
                if(menu.getId()!=null){
                    PageData pageData = new PageData();
                    pageData.put("menuName", menu.getMenuName());
                    pageData.put("menuUrl", "/" + menu.getMenuURL());
                    resultList.add(pageData);
                }

            }

        return resultList;
    }
}
